package com.glp.work.flow.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.glp.common.reponse.BaseResponse;
import com.glp.common.reponse.BaseResult;
import com.glp.fbs.api.dto.appInfo.AppUserReq;
import com.glp.fbs.api.dto.appInfo.AppUserResp;
import com.glp.fbs.api.dto.user.PersonInfoDto;
import com.glp.fbs.api.dto.user.PersonInfoWithAppReq;
import com.glp.work.flow.constant.APICode;
import com.glp.work.flow.dto.AppInfoResp;
import com.glp.work.flow.dto.RoleDTO;
import com.glp.work.flow.dto.UserDTO;
import com.glp.work.flow.dto.UserEntity;
import com.glp.work.flow.dto.request.PersonInfoReq;
import com.glp.work.flow.dto.request.RiskLevelQueryRequest;
import com.glp.work.flow.dto.request.UsersRequstDto;
import com.glp.work.flow.dto.response.RiskLevelQueryResponse;
import com.glp.work.flow.exception.APIException;
import com.glp.work.flow.pojo.RoleCodes;
import com.glp.work.flow.request.RoleRequest;
import com.glp.work.flow.response.RolesResponse;
import com.glp.work.flow.service.client.PermissionClient;
import com.glp.work.flow.service.client.RiskWarningClient;
import com.glp.work.flow.service.UserService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author zy
 * @date 2018年11月3日 15:23:48
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private PermissionClient permissionService;

    @Resource
    private RiskWarningClient riskWarningClient;

    @Value("${glp.fbs-app.appId}")
    private String appId;

    @Value("${glp.cash.management.tenantNo}")
    private String tenantNo;

    @Override
    public List<RoleDTO> queryUserRolesById(String userNo) {
        BaseResult result = permissionService.getRoleAndPermList(userNo, appId);
        if (!result.getCode().equals(APICode.SUCCESS.getCode())) {
            throw new APIException(APICode.ERROR, "调用认证系统获取用户角色及菜单错误；userNo= " + userNo);
        }
        Map<String, Object> obj = JSONArray.parseObject(JSONArray.toJSONString(result.getData()), Map.class);

        List<RoleDTO> list = new ArrayList();
        if (obj.containsKey("roles")) {
            list = JSONArray.parseArray(JSONArray.toJSONString(obj.get("roles")), RoleDTO.class);
        }

        return list;
    }

    @Override
    public BaseResult<UserDTO> getPersonInfo(String userNo) {
        BaseResult userResult = permissionService.getPersonInfo(userNo);
        if (!userResult.getCode().equals(APICode.SUCCESS.getCode())) {
            return null;
        }
        UserDTO user = JSONArray.parseObject(JSONArray.toJSONString(userResult.getData()), UserDTO.class);
        user.setTenantNo(tenantNo);
        return BaseResponse.success(user);
    }

    @Override
    public BaseResult<List<UserEntity>> getUserList(UserEntity user) {
        UsersRequstDto dto = new UsersRequstDto();
        List<UserEntity> data = Lists.newArrayList();
        dto.setAppId(appId);
        if (StringUtils.isNotBlank(user.getAppId())) {
            dto.setAppId(user.getAppId());
        }
        if (StringUtils.isNotBlank(user.getUserNo())) {
            dto.setUserNo(user.getUserNo());
        }
        BaseResult<List<UserEntity>> listResult = permissionService.userList(dto);
        List<UserEntity> users = listResult.getData();
        if (users == null) {
            log.error("获取用户信息失败,resp= {}", listResult);
            return listResult;
        }
        users.forEach(userEntity -> {
            boolean match = false;
            if (StringUtils.isNotEmpty(user.getUserNo()) && userEntity.getUserNo().contains(user.getUserNo())) {
                match = true;
            }
            if (StringUtils.isNotEmpty(user.getUserName()) && userEntity.getUserName().contains(user.getUserName())) {
                match = true;
            }
            if (match) {
                data.add(userEntity);
            }
        });
        return BaseResponse.success(data);
    }

    @Override
    public BaseResult getUserSingle(UserEntity user) {
        BaseResult<List<UserEntity>> users = getUserList(user);
        if (null != users.getData() && users.getData().size() > 0) {
            UserEntity userRsp = ((List<UserEntity>) users.getData()).get(0);
            return BaseResponse.success(userRsp);
        }
        return BaseResponse.success();
    }

    @Override
    public JSONArray getPersonSubordinate(String userNo) {
        BaseResult personInfo = permissionService.getPersonSubordinate(userNo);
        if (personInfo.getCode() != 200) {
            return null;
        }
        Object data = personInfo.getData();
        JSONArray objects = JSONArray.parseArray(JSON.toJSONString(data));
        return objects;
    }

    @Override
    public PersonInfoDto getPersonInfo(String createUserId, String appId) {
        BaseResult<PersonInfoDto> personInfo = permissionService.getPersonInfo(createUserId, appId);
        if (personInfo.getCode() != 200) {
            return null;
        }
        return personInfo.getData();
    }

    @Override
    public List<String> getPersonAllEnableRoles(String userNo) {
        BaseResult personAllEnableRoles = permissionService.getPersonAllEnableRoles(userNo);
        if (personAllEnableRoles.getCode() != 200) {
            throw new APIException(APICode.ERROR, "获取当前登录用户，所有的应用下角色信息失败！！");
        }
        Map data = (Map) personAllEnableRoles.getData();
        Object appRoles = data.get("appRoles");
        String str = JSON.toJSONString(appRoles);
        List<String> roleCodes = new ArrayList<>();
        List<Map> objects = JSONArray.parseArray(str, Map.class);
        for (Map o : objects) {
            Object roles = o.get("roles");
            String s = JSON.toJSONString(roles);
            JSONArray lists = JSONArray.parseArray(s);
            lists.forEach(role -> {
                Map map = JSONObject.parseObject(JSONObject.toJSONString(role), Map.class);
                String code = map.get("code").toString();
                roleCodes.add(code);
            });
        }
        return roleCodes;
    }

    @Override
    public List<UserDTO> personInfosByRoleCodeList(RoleCodes roleCodes) {
        BaseResult<?> listBaseResult = permissionService.personInfosByRoleCodeList(roleCodes);
        if (listBaseResult.getCode() != 200) {
            return null;
        }
        if (listBaseResult.getData() != null) {
            Object data = listBaseResult.getData();
            if (data != null) {
                List<UserDTO> userDTOList = new ArrayList<>();
                List<?> list = JSONObject.parseObject(JSONObject.toJSONString(data), List.class);
                for (Object o : list) {
                    UserDTO userDTO = new UserDTO();
                    JSONObject jsonObject = JSONObject.parseObject(o.toString());
                    userDTO.setUserNo(jsonObject.get("userNo").toString());
                    userDTO.setName(jsonObject.get("userName").toString());
                    userDTOList.add(userDTO);
                }
                return userDTOList;
            }
        }
        return null;
    }

    @Override
    public List<RolesResponse> enabledRoles(RoleRequest roleRequest) {
        BaseResult<List<RolesResponse>> listBaseResult = permissionService.enabledRoles(roleRequest);
        if (listBaseResult.getCode() != 200) {
            throw new APIException(APICode.ERROR, "调用应用下可用用的角色列表失败！！");
        }
        return listBaseResult.getData();
    }

    @Override
    public List<String> personRoles(String userNo, String appId) {
        BaseResult roleAndPermList = permissionService.personRoles(userNo, appId);
        if (roleAndPermList.getCode() != 200) {
            return null;
        }
        List<String> roleCodes = new ArrayList<>();
        if (roleAndPermList.getData() != null) {
            List<?> data = (List<?>) roleAndPermList.getData();
            data.forEach(o -> {
                Map<String, String> map = JSONObject.parseObject(JSONObject.toJSONString(o), Map.class);
                roleCodes.add(map.get("code").toString());
            });
        }
        return roleCodes;
    }

    @Override
    public List<UserDTO> getPersonInfos(String appId, PersonInfoReq req) {
        BaseResult personInfos = permissionService.getPersonInfos(appId, req);
        if (personInfos.getCode() != 200) {
            return null;
        }
        if (personInfos.getData() != null) {
            Object data = personInfos.getData();
            if (data != null) {
                List<UserDTO> userDTOList = new ArrayList<>();
                List<?> list = JSONObject.parseObject(JSONObject.toJSONString(data), List.class);
                for (Object o : list) {
                    UserDTO userDTO = new UserDTO();
                    JSONObject jsonObject = JSONObject.parseObject(o.toString());
                    userDTO.setUserNo(jsonObject.get("userNo").toString());
                    userDTO.setName(jsonObject.get("name").toString());
                    userDTO.setEmail(jsonObject.get("email").toString());
                    if (jsonObject.get("businessRangeCodes") != null) {
                        userDTO.setBusinessRangeCodes(jsonObject.get("businessRangeCodes").toString());
                    }
                    userDTOList.add(userDTO);
                }
                return userDTOList;
            }
        }
        return null;
    }

    @Override
    public AppInfoResp detailByAppId(String appId) {
        BaseResult<AppInfoResp> appInfoRespBaseResult = permissionService.detailByAppId(appId);
        if (appInfoRespBaseResult.getCode() != 200) {
            return null;
        }
        if (appInfoRespBaseResult.getData() != null) {
            return appInfoRespBaseResult.getData();
        }
        return null;
    }

    @Override
    public List<PersonInfoDto> getPersonInfos(PersonInfoReq req) {
        BaseResult<List<PersonInfoDto>> personInfos = permissionService.getPersonInfos(req);
        if (APICode.SUCCESS.getCode().equals(personInfos.getCode())) {
            return personInfos.getData();
        }
        return null;
    }

    @Override
    public List<AppUserResp> appInfoUsers(AppUserReq appUserReq) {
        BaseResult<List<AppUserResp>> appUserRespBaseResult = permissionService.appInfoUsers(appUserReq);
        if (APICode.SUCCESS.getCode().equals(appUserRespBaseResult.getCode())) {
            return appUserRespBaseResult.getData();
        }
        return null;
    }

    @Override
    public List<AppUserResp> getPersonWithBusinessList(PersonInfoWithAppReq req) {
        BaseResult<List<AppUserResp>> appUserRespBaseResult = permissionService.getPersonWithBusinessList(req);
        if (APICode.SUCCESS.getCode().equals(appUserRespBaseResult.getCode())) {
            return appUserRespBaseResult.getData();
        }
        return null;
    }

    @Override
    public List<RiskLevelQueryResponse> batchRiskLevel(RiskLevelQueryRequest request) {
        BaseResult<List<RiskLevelQueryResponse>> baseResult = riskWarningClient.batchRiskLevel(request);
        if(APICode.SUCCESS.getCode().equals(baseResult.getCode())){
            List<RiskLevelQueryResponse> data = baseResult.getData();
            return data;
        }
        return null;
    }

}
